package com.lyb269.thread;

import org.junit.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  Condition多线路通知功能,每条线路互不影响
 */
public class ConditionMultilineTest {

    private ReentrantLock lock = new ReentrantLock();

    //线路1 Condition
    private Condition lineCondition1 = lock.newCondition();

    //线路2 Condition
    private Condition lineCondition2 = lock.newCondition();

    //线路等待
    private void lineAwait(Condition condition){
        try{
            lock.lock();
            Thread currentThread = Thread.currentThread();
            long start = System.currentTimeMillis();
            System.out.println(currentThread.getName()+":执行lineAwait,进入等待");
            //await等待
            condition.await();

            //如果执行到这里说明线路被唤醒
            System.out.println(currentThread.getName()+":被唤醒");
            System.out.println(currentThread.getName()+":执行了"+(System.currentTimeMillis()-start)+"ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //线路唤醒
    private void lineSignalAll(Condition condition){
        try{
            lock.lock();
            //唤醒
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    @Test
    public void test() throws InterruptedException {
        Thread line1 = new Thread(() -> lineAwait(lineCondition1));
        Thread line2 = new Thread(() -> lineAwait(lineCondition2));

        new Thread(line1,"line1").start();
        new Thread(line2,"line2").start();

        // wait 2秒
        Thread.sleep(2000);
        // 唤醒line1
        lineSignalAll(lineCondition1);

        // wait 3秒
        Thread.sleep(3000);
        // 唤醒line2
        lineSignalAll(lineCondition2);

        //line1:执行lineAwait,进入等待
        //line2:执行lineAwait,进入等待

        //line1:被唤醒
        //line1:执行了2000ms

        //line2:被唤醒
        //line2:执行了5000ms

        //总结:
        //     线路1,线路2各自进入等待
        //     根据调用的顺序在sleep对应设置的时间之后各自唤醒,两条线路之间互不干涉,各自工作
    }
}
